package com.ruoyi.zxjd.conference.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.TimerTask;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zxjd.common.CommonConstants;
import com.ruoyi.zxjd.common.domain.CommonUserVO;
import com.ruoyi.zxjd.common.mapper.CommonMapper;
import com.ruoyi.zxjd.conference.domain.ConferenceArrange;
import com.ruoyi.zxjd.conference.domain.ConferenceParticipant;
import com.ruoyi.zxjd.conference.mapper.ConferenceArrangeMapper;
import com.ruoyi.zxjd.conference.mapper.ConferenceParticipantMapper;
import com.ruoyi.zxjd.work.domain.WorkHandle;
import com.ruoyi.zxjd.work.domain.WorkProgress;
import com.ruoyi.zxjd.work.service.IWorkHandleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.zxjd.conference.mapper.ConferenceProgressMapper;
import com.ruoyi.zxjd.conference.domain.ConferenceProgress;
import com.ruoyi.zxjd.conference.service.IConferenceProgressService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.Size;

/**
 * 填报进度Service业务层处理
 * 
 * @author lcc
 * @date 2021-02-07
 */
@Service
public class ConferenceProgressServiceImpl implements IConferenceProgressService 
{
    @Resource
    private ConferenceProgressMapper conferenceProgressMapper;

    @Resource
    private ConferenceArrangeMapper conferenceArrangeMapper;

    @Resource
    private ConferenceParticipantMapper conferenceParticipantMapper;

    @Resource
    private ISysUserService userService;

    @Resource
    private CommonMapper commonMapper;

    @Autowired
    private IWorkHandleService workHandleService;

    /**
     * 查询填报进度
     * 
     * @param progressId 填报进度ID
     * @return 填报进度
     */
    @Override
    public ConferenceProgress selectConferenceProgressById(Long progressId)
    {
        return conferenceProgressMapper.selectConferenceProgressById(progressId);
    }

    /**
     * 查询填报进度列表
     * 
     * @param conferenceProgress 填报进度
     * @return 填报进度
     */
    @Override
    public List<ConferenceProgress> selectConferenceProgressList(ConferenceProgress conferenceProgress)
    {
        return conferenceProgressMapper.selectConferenceProgressList(conferenceProgress);
    }

    /**
     * 新增填报进度
     * 
     * @param conferenceProgress 填报进度
     * @return 结果
     */
    @Override
    @Transactional
    public int insertConferenceProgress(ConferenceProgress conferenceProgress)
    {
        int j=0;
        //发起人
        SysUser sysUser1 = userService.selectUserByLoginName(ShiroUtils.getLoginName());
        String releaseScope = conferenceProgress.getReleaseScope();
        String[] userNames = releaseScope.split(" ");
        String[] ids = new String[0];
        ConferenceArrange conferenceArrange = conferenceArrangeMapper.selectConferenceArrangeById(conferenceProgress.getArrangeId());
        List<CommonUserVO> list = null;
        for (String userName : userNames) {
            int a = conferenceParticipantMapper.selectConferenceParticipantByName(userName);
            if (0!=a){
                //此人已填报
            }else {
                //新增接收人员
                SysUser sysUser = userService.selectUserByName(userName);
                ids = Arrays.copyOf(ids, ids.length + 1); // 数组增加一个长度
                ids[ids.length - 1] = sysUser.getUserId()+"";
                conferenceProgress.setArrangeName(conferenceArrange.getArrangeName());
                conferenceProgress.setCreateBy(conferenceArrange.getCreateBy());
                conferenceProgress.setCreateTime(conferenceArrange.getCreateTime());
                conferenceProgress.setReceiveUserId(sysUser.getUserId());
                conferenceProgress.setReceiveUser(userName);
                conferenceProgress.setReceiveDeptId(sysUser.getDeptId());
                conferenceProgress.setReceiveDept(sysUser.getDept().getDeptName());
                conferenceProgress.setLastFullTime(conferenceArrange.getLastFullTime());
                conferenceProgress.setStatus("0");
                conferenceProgress.setUserId(sysUser1.getUserId());
                conferenceProgress.setUserName(sysUser1.getUserName());
                conferenceProgress.setDeptId(sysUser1.getDeptId());
                conferenceProgress.setDeptName(sysUser1.getDept().getDeptName());
                conferenceProgressMapper.insertConferenceProgress(conferenceProgress);

            }
        }
        j++;
        conferenceProgress.setUserIds(ids);
        String[] userIds = conferenceProgress.getUserIds();
        if(CommonConstants.AllUSER.equals(releaseScope)){
            list = commonMapper.listActiveUser(null,null);
        }else{
            list = commonMapper.listActiveUserByIds(userIds);
        }
        j++;
        //短信提示
        if (StringUtils.equals(CommonConstants.TIPS, conferenceProgress.getSmsTips())) {
            AsyncManager.me().execute(createSmsTips(conferenceArrange.getArrangeName(), list,conferenceArrange));
        }
        //平台提示
        if (StringUtils.equals(CommonConstants.TIPS, conferenceProgress.getWebsiteTips())) {
            AsyncManager.me().execute(createWebsiteTips(list, 1));
        }
        j++;
        return j;
    }

    private TimerTask createSmsTips(String arrangeTitle, List<CommonUserVO> list, ConferenceArrange conferenceArrange) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    String message = commonUserVO.getUserName()+"，您好！在线监督平台提示:会议名为:"+conferenceArrange.getArrangeName()+"的会议，会议时间为"+conferenceArrange.getStartTime()+"——"+conferenceArrange.getEndTime()+"，报名时间截止"+conferenceArrange.getLastFullTime();
                    String mobileNo = commonUserVO.getPhonenumber();
                    if(StringUtils.isNotEmpty(mobileNo)){
                        SmsUtil.sendMessage(message, mobileNo);
                    }
                }
            }
        };
    }

    private TimerTask createWebsiteTips(List<CommonUserVO> list, int num) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    WorkHandle workHandle = new WorkHandle();
                    workHandle.setUserId(commonUserVO.getUserId());
                    workHandle.setType(CommonConstants.WORK);
                    workHandleService.insertOrUpdateWorkHandle(workHandle, num); //工作项+1
                }
            }
        };
    }

    /**
     * 修改填报进度
     * 
     * @param conferenceProgress 填报进度
     * @return 结果
     */
    @Override
    public int updateConferenceProgress(ConferenceProgress conferenceProgress)
    {
        conferenceProgress.setUpdateBy(userService.selectUserByLoginName(ShiroUtils.getLoginName()).getUserName());
        conferenceProgress.setUpdateTime(DateUtils.getNowDate());
        SysUser sysUser = userService.selectUserByName(conferenceProgress.getReceiveUser());
        @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符") String phonenumber = sysUser.getPhonenumber();
        String sms=conferenceProgress.getReceiveUser()+"您好！在线监督平台提示:您的会议填报信息已被修改，请注意查收";
        SmsUtil.sendMessage(sms,phonenumber);
        return conferenceProgressMapper.updateConferenceProgress(conferenceProgress);
    }

    /**
     * 删除填报进度对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteConferenceProgressByIds(String ids)
    {
        conferenceProgressMapper.deleteConferenceParticipantByIds(Convert.toStrArray(ids));
        return conferenceProgressMapper.deleteConferenceProgressByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除填报进度信息
     * 
     * @param progressId 填报进度ID
     * @return 结果
     */
    @Override
    public int deleteConferenceProgressById(Long progressId)
    {
        return conferenceProgressMapper.deleteConferenceProgressById(progressId);
    }

    /**
     * 校验提交日期并更新工作进度状态
     * @param conferenceProgress
     */
    public int validate(ConferenceProgress conferenceProgress){
        /*ConferenceProgress OldConferenceProgress = conferenceProgressMapper.selectConferenceProgressById(conferenceProgress.getProgressId());
        if (StringUtils.equals(CommonConstants.ENABLE, conferenceProgress.getStatus())) {
            String nowDate = DateUtils.getDate();
            String endDate = DateUtils.parseDateToStr("yyyy-MM-dd", OldConferenceProgress.getLastFullTime());
            if(StringUtils.compare(nowDate, endDate)>0){
                conferenceProgress.setStatus(CommonConstants.DRAFT);
            }
            // 更新上报人数
            conferenceArrangeMapper.updateUnfillTotal(oldWorkProgress.getArrangeId(),-1);
            // 更新未处理项
            workHandleMapper.updateUntreatedTotal(oldWorkProgress.getReceiveUserId(),CommonConstants.WORK,-1);
        }
        return this.updateWorkProgress(workProgress);*/
        return 1;
    }

    @Override
    public int deleteConferenceProgressByArrangeId(long arrangeId) {
        return conferenceProgressMapper.deleteConferenceProgressByArrangeId(arrangeId);
    }
}
